# encoding:utf-8
from __future__ import unicode_literals

from ..field_proc  import BaseFieldProc
from django.db.models import ImageField
from .. .base_data import field_map
#from django.utils.translation import gettext as _
from django.utils.translation import gettext as _
from ...func.url_path import add_media_url,clear_media_url,media_url_to_path
from django.db.models.fields.files import ImageFieldFile
from django.core.files import File
import os

class ImageFieldProc(BaseFieldProc):
    '''
    接收图片，以md5的形式，存储在public/images,默认folder是head['up_url']='/d/upload?path=public/images'
    如果要
    '''
    
    def to_dict(self,inst,name):
        """返回字典
        to_dict 函数会调用这个方法
        """
        value = getattr(inst,name)
        if isinstance(value,ImageFieldFile):
            if value:
                #有可能是空文件
                return {name:value.url}
            else:
                return {name:''}
        
        if isinstance(value,str):
            return {name:value.strip()}
        else:
            return { name :value}
       
    def clean_field(self,dc,name):
        """
        """
        value = dc.get(name)
        naked_path = clear_media_url(value)
        #if isinstance(value,str):
            #naked_path = clear_media_url(value)
            #full_path = media_url_to_path(value)
            #if os.path.exists(full_path):
                #with open(full_path, 'rb') as f:
                    #return File(f, name=naked_path)
        return naked_path
        
        #return File

    def dict_table_head(self,head): 
        head['editor']='com-table-picture'
        head['show_tooltip'] = False
        return head
    
    def dict_field_head(self,head):
        head['editor']='com-field-picture'
        #head['up_url']='/d/upload?path=general_upload/images'
        head['up_url']='/d/upload?path=general_upload/images'
        #head['config']={
            #'up_url':'/d/upload?path=public/images'
        #}
        return head


field_map.update({
    ImageField:ImageFieldProc
})



